﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TmU220PrintHelperV2d0.Entity;
using TmU220PrintHelperV2d0.Service;
using ZhangLogSysV1d0;

namespace TmU220PrintHelperV2d0.Singleton
{
    public class UpdateDataKeyValueDataNetSingletonV1d0
    {
        private static UpdateDataKeyValueDataNetSingletonV1d0 _instance = null;
        private ThinkPhpApiV1d0 _phpApi = null;
        private static readonly object syslock = new object();
        /// <summary>
        /// 单例模式
        /// </summary>
        public static UpdateDataKeyValueDataNetSingletonV1d0 Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (syslock)
                    {
                        if (_instance == null)
                        {
                            _instance = new UpdateDataKeyValueDataNetSingletonV1d0();
                        }
                    }
                }
                return _instance;
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        private UpdateDataKeyValueDataNetSingletonV1d0()
        {
            _phpApi = new ThinkPhpApiV1d0();
            LoadData();
        }
        /// <summary>
        /// 装载数据
        /// </summary>
        private void LoadData()
        {
            ReloadData();
        }
        /// <summary>
        /// 从配置文件中，读取组内的接口
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="apiName"></param>
        public void ReloadData(string groupName = "TaskApi", string apiName = "updateDataKeyValueDataNet")
        {
            _phpApi = PhpApiSetSingletonV1d0.Instance.GetApi(groupName, apiName);
        }

        /// <summary>
        /// 执行接口
        /// </summary>
        /// <typeparam name="T">类名称</typeparam>
        /// <param name="data">uid等于0时，有php服务器自动计算uid</param>
        /// <returns></returns>
        public bool Run<T>(string key,string value,T data)
        {
            bool result = false;
            try
            {
                //接口url
                string url = _phpApi.main_url + _phpApi.method_name;
                //根据类，得到类名称，内部约定类名称就是对应数据表的表名
                string tableName = typeof(T).Name;
                string jsonStringOfData = JsonConvert.SerializeObject(data);
                //动态类型
                dynamic dataDynamic = data;
                //int uid = dataDynamic.uid;
                string paramString = string.Format("tablename={0}&key={1}&value={2}&data={3}", tableName, key,value, jsonStringOfData);
                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 5000;
                request.AddParameter(contentType, paramString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        /// <summary>
        /// 运行接口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="jsonStringOfData"></param>
        /// <returns></returns>
        public bool Run(string tableName,string key, string value, string jsonStringOfData)
        {
            bool result = false;
            try
            {
                //接口url
                string url = _phpApi.main_url + _phpApi.method_name;
                string paramString = string.Format("tablename={0}&key={1}&value={2}&data={3}", tableName, key, value, jsonStringOfData);
                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 5000;
                request.AddParameter(contentType, paramString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
    }
}
